from const import * 
import os
from shutil import copyfile

def check_if_download_files(dict_values):
    save_files=[]
    for k,v in dict_values.items():
        if str(k).startswith('_checkbox_') and v:
            save_files.append(k)
    return save_files

def modal_window(sg,pdf_folder:dict,title:str):
    # sg.theme('DarkAmber')
    
    col=[]
    # for index,row in enumerate(cert_rows):
    #     col.append([
    #         sg.Text('{}:'.format(row),size=(16,1)), 
    #         sg.Checkbox(f'{index}a.pdf',key=f'_checkbox_{index}')
    #         ])
    i = 0
    disabled = True
    print(f'row: {pdf_folder}')
    # for k,v in pdf_folder.items():
    #     _col = [sg.Text('{}:'.format(k),size=(16,1))]
    #     if len(v[0]) == 0:
    #         _col.append(sg.Text('无'))
    #     for pdf in v[0]:
    #         disabled = False
    #         i+=1
    #         print(f'PDF: {pdf}  pdf_fpath:{v[1]}')
    #         _col.append(sg.Checkbox(f'{pdf}',key=f'_checkbox_{i}',metadata=v[1]))
    #     col.append(_col)
    for k,v in pdf_folder.items():
        _col=[]
        for pdf in v[0]:
            i +=1
            _col.append(sg.Checkbox(f'{pdf}',key=f'_checkbox_{i}',metadata=v[1]))
        col.append(_col)
        disabled = False
    layout = [
        [
            sg.Column(col)
        ],
        [
            sg.InputText(visible=False, enable_events=True, key='_event_trigger_'),
            sg.FolderBrowse('保存到文件夹:',key='_folder_path_',disabled=disabled),
            sg.Text(size=(16,1),key='_show_path_')
        ]
        
            ]
    # Create the Window
    window = sg.Window(f'[{title}]证件信息展示', layout,disable_minimize=True,font=font)
    window.Finalize()
    window.TKroot.transient()
    window.TKroot.grab_set()
    window.TKroot.focus_force()
    # Event Loop to process "events" and get the "values" of the inputs
    while True:
        event, values = window.read()

        if (event == '_event_trigger_') and (values['_folder_path_'] != ''):
            no_select_chkbox = False
            dir_to_save=values['_folder_path_']
            for chk_element in check_if_download_files(values):
                no_select_chkbox = True
                print('Saving :{} from dir [{}] to dir [{}]'.format(
                    window.Element(chk_element).Text,
                    window.Element(chk_element).metadata,
                    dir_to_save
                    ))
                try:
                    copyfile(os.path.join(window.Element(chk_element).metadata,window.Element(chk_element).Text),
                    os.path.join(dir_to_save,window.Element(chk_element).Text))
                except:
                    print('error to copy')
            if not no_select_chkbox:
                sg.PopupError('请至少选择一个要下载的文件!',keep_on_top=True,auto_close=True)
                continue
        if event is None:
            break
        print('You entered ', event,values)
        window.Element('_show_path_').update('{}'.format(values['_folder_path_']))

    window.close()
if __name__ == "__main__":
    import PySimpleGUI as sg
    modal_window(sg,None,'test')
    